#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>

using namespace std;

int main()
{
	int x = 0;
	bool flag = false;
	condition_variable cv;
	mutex _mtx;
	thread t1([&]() {
		for (int i = 0; i < 100; i++)
		{
			unique_lock<mutex> lock(_mtx);
			if (flag)
			{
				cv.wait(lock);
			}
			++x;
			cout << this_thread::get_id() << ": " << x << endl;

			flag = true;
			cv.notify_one();
			std::this_thread::sleep_for(std::chrono::seconds(1));
		}
	});

	thread t2([&]() {
		for (int i = 0; i < 100; i++)
		{
			unique_lock<mutex> lock(_mtx);
			if (!flag)
			{
				cv.wait(lock);
			}

			++x;
			cout << this_thread::get_id() << ": " << x << endl;

			flag = false;
			cv.notify_one();
			std::this_thread::sleep_for(std::chrono::seconds(1));
		}
	});
	t1.join();
	t2.join();
}